package com.frxuexi.mdm2204.myview

import android.animation.ObjectAnimator
import android.content.Context
import android.util.AttributeSet
import android.widget.ImageView
import android.widget.RelativeLayout
import com.frxuexi.mdm2204.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.util.Timer
import kotlin.concurrent.timerTask
import kotlin.random.Random

class HongbaoView : RelativeLayout {
    lateinit var timer: Timer

    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)

    fun start() {
        timer = Timer()
        timer.schedule(timerTask {
            GlobalScope.launch(Dispatchers.Main) {
                var iv = ImageView(context)
                iv.setImageResource(R.drawable.hb)

                val params = LayoutParams(100, 200)
                val num = Random.nextInt(1000)
                params.leftMargin = num
                params.topMargin = 0
                iv.layoutParams = params

                val animator = ObjectAnimator.ofFloat(iv, "translationY", 0f, 2000f)
                animator.setDuration(5000)
                animator.start()
                addView(iv)
            }


        }, 0, 200)
    }

    fun stop(){
        timer.cancel()
    }
}
